import 'dart:io';

import 'package:azlistview/azlistview.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jetour_line/aha_jetour_line.dart';
import 'package:jetour_line/base_widget/base_image.dart';
import 'package:jetour_line/base_widget/loading_widget.dart';
import 'package:jetour_line/network/aha_http.dart';
import 'package:jetour_line/utils/aha_utils.dart';
import 'package:jetour_line/utils/double_extension.dart';
import 'package:jetour_line/utils/extension_int.dart';

import '../../base_widget/base_scaffold.dart';
import '../../model/city_list_model.dart';
import '../../my_colors.dart';

const Color bgColor = Colors.black87;
const double radius = 3.0;

typedef _ChooseCityCallBack = void Function(String city, String cityId);

class ChooseCityScreen extends StatefulWidget {
  static const String routeName = "ChooseCityScreen";

  ChooseCityScreen();

  @override
  _ChooseCityState createState() => _ChooseCityState();
}

class _ChooseCityState extends State<ChooseCityScreen> {
  List<CityModel>? _cityList;

  double _suspensionHeight = 40;
  double _itemHeight = 50;
  String _suspensionTag = "";
  CityListModel? cityListModel;
  List<CityModel> searchList = [];
  String? cityName;

  int? cityId;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (MapUtils.locationInfoModel != null) {
      cityName = MapUtils.locationInfoModel?.component.city;
      cityId = MapUtils.locationInfoModel?.component.cityId;
    }
    _loadData();
  }

  void _loadData() async {
    AhaHttp().get(AhaRouter.CityList).then((value) {
      _cityList = [];
      cityListModel = CityListModel.fromJson(value);
      for (CityList list in cityListModel!.cityList) {
        for (CityModel city in list.city) {
          _cityList!.add(CityModel(
              name: city.name, prefix: list.prefix, id: city.id, pinyin: ''));
        }
      }
      SuspensionUtil.setShowSuspensionStatus(_cityList);
      _cityList!
          .insert(0, CityModel(name: 'header', prefix: '★', id: 0, pinyin: ''));
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      hidenAppBar: true,
      body: Column(children: [
        titleWidget(),
        SizedBox(height:10.px),
        _cityList == null
            ? Padding(padding: EdgeInsets.only(top: AhaUtils.getAppBarHeight(context)), child: LoadingWidget())
            : searchList.isNotEmpty
            ? serchResultWidget()
            : Expanded(
              child: AzListView(
          data: _cityList!,
          itemCount: _cityList!.length,
          itemBuilder: (BuildContext context, int index) {
              if (index == 0) return _buildHeader();
              CityModel model = _cityList![index];
              return _buildListItem(model);
          },
          physics: BouncingScrollPhysics(),
          susItemHeight: _suspensionHeight,
          susItemBuilder: (BuildContext context, int index) {
              CityModel model = _cityList![index];
              String tag = model.getSuspensionTag();
              if ('★' == model.getSuspensionTag()) {
                return Container();
              }
              return _buildSusWidget(tag);
          },
          indexBarData: SuspensionUtil.getTagIndexList(_cityList),
          indexHintBuilder: (context, hint) {
              return Container(
                alignment: Alignment.center,
                width: 80.0,
                height: 80.0,
                decoration: BoxDecoration(
                    color: MyColors.appColor, shape: BoxShape.circle),
                child: Text(hint,
                    style:
                    TextStyle(color: Colors.white, fontSize: 50.px)),
              );
          },
        ),
            ),
      ],)
    );
  }

  Widget titleWidget() {
    return Container(

      padding: EdgeInsets.only(bottom: 6),
      alignment: Alignment.bottomLeft,
      width: double.infinity,
      color: Colors.white,
      height: AhaUtils.getAppBarHeight(context),
      child: Row(
        children: [
          GestureDetector(
            onTap: (){
              Navigator.pop(context);
            },
            child: Padding(
                padding: EdgeInsets.only(left: 26.rpx,right: 24.px),
                child: const BaseImage(image: 'back_icon',width: 20,height: 20,)),
          ),
          Expanded(
            child: ClipRRect(
              borderRadius: const BorderRadius.all(Radius.circular(20)),
              child: Container(
                color: MyColors.colorF1F1F1,
                alignment: Alignment.centerLeft,
                width: double.infinity,
                height: 34,
                child: Padding(
                  padding: const EdgeInsets.only(left: 10, right: 10),
                  child: TextField(
                    onChanged: (value) {
                  if (_cityList!.isNotEmpty) {
                    // ignore: unnecessary_null_comparison
                    if (value == null || value.isEmpty) {
                      searchList = [];
                    } else {
                      List<CityModel> sList = [];
                      for (CityModel model in _cityList!) {
                        if (model.name.contains(value)) {
                          sList.add(model);
                        }
                      }
                      searchList = [];
                      searchList.addAll(sList);
                    }
                    setState(() {});
                  }
                    },
                    style:
                    TextStyle(fontSize: 28.px, color: MyColors.color333333),
                    decoration: const InputDecoration(
                  border: InputBorder.none,
                  hintText: '请输入关键词',
                  isDense: true,
                  contentPadding: EdgeInsets.fromLTRB(8, 0, 0, 0),
                    ),
                  ),
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              FocusScope.of(context).unfocus();
            },
            child: Container(
              color: Colors.transparent,
              padding: const EdgeInsets.only(left: 30),
              child: const Text(
                '搜索',
                style: TextStyle(fontSize: 17, color: Colors.black),
              ),
            ),
          ),
          SizedBox(width: 24.px,)
        ],
      ),
    );
  }

  Widget _buildHeader() {
    List<CityModel> hotCityList = [];
    for (Hot hot in cityListModel!.hot) {
      hotCityList.add(
        CityModel(name: hot.name, id: hot.id, pinyin: '', prefix: ''),
      );
    }
    return Padding(
      padding: EdgeInsets.only(left: 20.px),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (cityName != null)
            Padding(
              padding: EdgeInsets.only(top: 30.px, bottom: 40.px),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      '当前城市',
                      style: TextStyle(
                          fontSize: 32.px,
                          color: MyColors.color333333,
                          fontWeight: FontWeight.w600),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      selAction(CityModel(
                          pinyin: '',
                          id: cityId!,
                          prefix: null,
                          name: cityName!));
                    },
                    child: Container(
                      color: Colors.transparent,
                      child: Row(
                        children: [
                          BaseImage(
                            image: 'icon_addressblack',
                            width: 48.px,
                            height: 48.px,
                          ),
                          Text(
                            cityName!,
                            style: TextStyle(
                                fontSize: 30.px, color: MyColors.color333333),
                          ),
                          SizedBox(
                            width: 40.px,
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          Text(
            '热门城市',
            style: TextStyle(
                fontSize: 32.px,
                color: MyColors.color333333,
                fontWeight: FontWeight.w600),
          ),
          SizedBox(
            height: 10.px,
          ),
          Padding(
            padding: EdgeInsets.only(top: 20.px, left: 20.px, right: 20.px),
            child: Wrap(
              alignment: WrapAlignment.start,
              runAlignment: WrapAlignment.center,
              spacing: 10.0,
              children: hotCityList.map((e) {
                return GestureDetector(
                  onTap: () {
                    selAction(e);
                  },
                  child: Padding(
                    padding: EdgeInsets.only(bottom: 15.px),
                    child: Container(
                      padding: EdgeInsets.only(
                          left: 15.px, right: 15.px, top: 8.px, bottom: 8.px),
                      decoration: BoxDecoration(
                        //设置四周圆角 角度
                        borderRadius: BorderRadius.all(Radius.circular(4.0.px)),
                        //设置四周边框
                        border:
                            Border.all(width: 1, color: MyColors.color999999),
                      ),
                      child: Text(
                        e.name,
                        style: TextStyle(
                            fontSize: 26.px, color: MyColors.color333333),
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildSusWidget(String susTag) {
    /// group 高度
    return Container(
      height: _suspensionHeight,
      width: MediaQuery.of(context).size.width,
      padding: const EdgeInsets.only(left: 15.0),
      color: Color(0xfff3f4f5),
      alignment: Alignment.centerLeft,
      child: Text(
        '$susTag',
        softWrap: false,
        style: TextStyle(
          fontSize: 30.px,
          color: Color(0xff999999),
        ),
      ),
    );
  }

  Widget _buildListItem(CityModel model) {
    String susTag = model.getSuspensionTag();
    return Column(
      children: <Widget>[
        SizedBox(
          height: _itemHeight,
          child: ListTile(
            title: Text(
              model.name,
              style: TextStyle(fontSize: 30.px, color: MyColors.color666666),
            ),
            onTap: () {
              selAction(model);
            },
          ),
        )
      ],
    );
  }

  Widget serchResultWidget() {
    return Expanded(
      child: ListView.builder(
          itemCount: searchList.length,
          itemBuilder: (context, index) {
            return GestureDetector(
              onTap: (){
                selAction(searchList[index]);
              },
              child: Container(
                padding: EdgeInsets.only(left: 40.px),
                color: Colors.transparent,
                width: double.infinity,
                height: 80.px,
                child: Text(
                  searchList[index].name,
                  style: TextStyle(fontSize: 30.px, color: MyColors.color666666),
                ),
              ),
            );
          }),
    );
  }

  void selAction(CityModel model) {
    Navigator.pop(context, model);
  }
}
